<template>
  <section class="newest">
    <h2 class="newest-title">
      <span class="newest-title__item newest-title_album"
        :class="{'bold': active !== 'song'}"
        @click="extractData('album')"
      >新碟</span>
      <span class="newest-title__item newest-title__song"
        :class="{'bold': active === 'song'}"
        @click="extractData('song')"
      >新歌</span>
    </h2>

    <div class="newest-content"
      v-loading="loading"
      m-loading-text="加载中..."
      m-loading-vertical="20px"
      m-loading-background="#fff">
      <multiline-swiper :list="list" />
    </div>
  </section>
</template>

<script>
import MultilineSwiper from '@/components/MultilineSwiper'
import { formatArtists } from '@/utils'

export default {
  name: 'home-newest',
  components: { MultilineSwiper },
  data () {
    return {
      loading: true,
      active: 'album',
      list: []
    }
  },
  mounted () {
    this.extractData(this.active)
  },
  methods: {
    extractData (type) {
      this.loading = true
      this.active = type

      if (this.$storage.hasCache(`home-new-${type}`)) {
        const { data } = this.$storage.getItem(`home-new-${type}`)
        this.loading = false
        this.list = Object.freeze([].concat(data))
        return
      }

      const promise = type === 'song'
        ? this.$api.getTopSong()
        : this.$api.getAlbumNewest()

      promise.then(res => {
        this.loading = false
        const data = type === 'song'
          ? res.data.data
          : res.data.albums
        const list = data.slice(0, 9).map(v => {
          const { id, name, description } = v
          const blurPicUrl = type === 'song'
            ? v.album.blurPicUrl + '?param=200y200'
            : v.blurPicUrl + '?param=200y200'
          const artists = formatArtists(v.artists)
          return { id, name, blurPicUrl, artists, description, type }
        })
        this.list = Object.freeze([].concat(list))
        this.$storage.setItem(`home-new-${type}`, this.list, true, {
          maxAge: 5 * 60 * 1000
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.newest {
  height: 2.75rem;
  &-title {
    height: .5rem;
    line-height: .5rem;
    font-size: $font--medium;
    &__item {
      margin: 0 .1rem;
      &.bold {
        font-weight: bold;
      }
    }
  }
  &-content {
    position: relative;
    height: 100%;
  }
}
</style>
